<?php
/******************************************************************************
*                                                                             *
* Steak Desk v0.2                                                             *
*                                                                             *
* Copyright (c) 2011 Andrew D. Zonenberg.                                     *
* All rights reserved.                                                        *
*                                                                             *
* Redistribution and use in source and binary forms, with or without modifi-  *
* cation, are permitted provided that the following conditions are met:       *
*                                                                             *
*    * Redistributions of source code must retain the above copyright notice  *
*      this list of conditions and the following disclaimer.                  *
*                                                                             *
*    * Redistributions in binary form must reproduce the above copyright      *
*      notice, this list of conditions and the following disclaimer in the    *
*      documentation and/or other materials provided with the distribution.   *
*                                                                             *
*    * Neither the name of the author nor the names of its contributors may be*
*      used to endorse or promote products derived from this software without *
*      specific prior written permission.                                     *
*                                                                             *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF        *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN     *
* NO EVENT SHALL THE AUTHOR BE HELD LIABLE FOR ANY DIRECT, INDIRECT,          *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT*
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, *
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF   *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING        *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS          *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                *
*                                                                             *
*******************************************************************************/

$g_start = microtime(true);
$g_querycount = 0;

//Pull in config
require_once('../config/config.inc.php');
require_once('../inc/enum.php');
$g_dbconn = null;
$g_tplvars = array();

define('VCS_SVN', 1);

//Load various helper functions
require_once('../inc/template.php');
require_once('menu.php');
require_once('../inc/vcs.php');

/**
	@brief Throws an error, verbosity depends on $g_config['dberrs']
 */
function dberror($query)
{
	global $g_config;
	global $g_dbconn;
	if($g_config['dberrs'])
		die('Database error: ' . mysql_error($g_dbconn) . "\n" . 'query = ' . "\n" . $query);
	else
		die('Database error');
}

/**
	@brief Runs a database query and checks for error
 */
function dbquery($q)
{
	global $g_dbconn;
	global $g_querycount;
	$g_querycount ++;
	$ret = mysql_query($q, $g_dbconn);
	if(!$ret)
		dberror($q);
	return $ret;
}

/**
	@brief Performs global initialization
 */
function init()
{
	//Magic quotes is dumb, turn it off
	if(get_magic_quotes_gpc())
		die('Magic quotes must be disabled');
	
	//connect to database
	global $g_config;
	global $g_dbconn;
	global $g_tplvars;
	$g_dbconn = mysql_connect($g_config['dbhost'], $g_config['dbuser'], $g_config['dbpass']);
	if(!$g_dbconn)
		dberror();
		
	//select db
	mysql_select_db($g_config['dbname']);
	
	//create session
	session_start();
	if(!isset($_SESSION['uid']))
		$_SESSION['uid'] = -1;
	else if($_SESSION['uid'] > 0)
		$g_tplvars['logout'] = 'Log out';
		
	//Set some default template variables
	$g_tplvars['sidemenu'] = sidemenu();
	$g_tplvars['topmenu'] = topmenu();
	$g_tplvars['titlebase'] = $g_config['sitename'];
	$g_tplvars['company'] = $g_config['company'];
}

/**
	@brief Check if we're logged in, if not show the login form and exit
 */
function restricted()
{
	if($_SESSION['uid'] < 0)
		loginform();
}

/**
	@brief Shows the login form and exits
 */
function loginform()
{
	global $g_tplvars;
	$g_tplvars['title'] = 'Log In';
	if(isset($_GET['loginfail']))
		$g_tplvars['failmsg'] = '<span class=\'error\'>Bad username or password</span>';
	render('../templates/loginform.html');
	exit;
}

/**
	@brief Removes nasty stuff from a string
	
	@param $str string to sanitize
	@return escaped string
 */
function sanitize_db($str)
{
	return mysql_real_escape_string($str);
}

/**
	@brief Removes nasty stuff from a string
	
	@param $str string to sanitize
	@return escaped string
 */
function sanitize_render($str)
{
	return str_replace('\\\'', '&apos;', htmlspecialchars($str));
}

/**
	@brief Prints out a timestamp in a nice user-friendly manner
 */
function format_date($timestamp)
{
	$now = time();
	$dt = $now - $timestamp;
	
	$daylen = 86400;
	
	$desc = '';
	if(date('m/d/Y', $now) == date('m/d/Y', $timestamp) )
	{
		if($dt < 3600)
			$desc = intval($dt / 60) . ' minutes ago';
		else
			$desc = intval($dt / 3600) . ' hours ago';
	}
	else if(date('m/d/Y', $now - $daylen) == date('m/d/Y', $timestamp) )
		$desc = 'Yesterday';
	else if($dt < 7*$daylen)
		$desc = date('l', $timestamp);
	else if(date('m/Y', $now) == date('m/Y', $timestamp) )
		$desc = intval($dt / $daylen) . ' days ago';
	else if(date('Y', $now) == date('Y', $timestamp))
		$desc = (intval(date('m',$now)) - intval(date('m',$timestamp))) . ' months ago';

	return $desc . ' <span class=\'fulldate\'>(' . date('m/d/Y H:i:s', $timestamp) . ')</span>';
}

/**
	@brief Converts a user ID into a user name
 */
function uid_to_name($uid)
{
	//First, find the user
	$r = dbquery('select * from users where `uid` = \'' . $uid . '\'');
	if(mysql_num_rows($r) != 1)
		return '';
	$u = mysql_fetch_object($r);
	return $u->name;
}

function checkinvaccess($ask)
{
	//See what privileges we have
	$access = enum_value_to_name('invaccess', 'none');
	$r = dbquery('select * from users where `uid` = \'' . $_SESSION['uid'] . '\'');
	if(mysql_num_rows($r) == 1)
	{
		$u = mysql_fetch_object($r);
		$access = $u->invaccess;
	}
	
	$ask = enum_name_to_value('invaccess', $ask);
	
	if($ask <= $access)
		return;
		
	//die
	global $g_tplvars;
	$g_tplvars['title'] = 'Access denied';
	render('../templates/access-denied.html');
	exit;
}

/**
	@brief Returns a set of option tags for a directory
 */
function pathlist($path, $skips)
{
	$ret = '';
	$dir = opendir($path);
	while($f = readdir($dir))
	{
		if($f[0] == '.')
			continue;
			
		$fname = $path . '/' . $f;
		if(is_dir($fname))
			$ret .= pathlist($fname, $skips);
		else if($f == 'pagecount.txt' || $f == 'pagecount.php')
			continue;
		else if(!isset($skips[$fname]) || $skips[$fname] == 0)
			$ret .= '<option value=\'' . $fname . '\'>' . $fname . '</option>' . "\n";
	}
	closedir($dir);
	return $ret;
}

//all app code is in main()
init();
main();

?>
